// 请求响应拦截
import axios from 'axios'
import store from '../store'
import { Message } from 'element-ui'
import { loginOut } from './logout'

const [
  SUCCESS_CODE,
  ERROR_CODE,
  HTTP_SUCCESS_CODE,
  TOKEN_OVER_CODE,
  LOG_OUT
] = [0, 1, 200, 401,  204]

const instance = axios.create({
  // 默认请求地址，根据环境的不同可在.env 文件中进行修改
  baseURL: window.VUE_APP_BASE_API,
  // 设置接口访问超时时间
  timeout: window.REQUEST_TIMEOUT,
  // 跨域时候允许携带凭证
  withCredentials: true
})

const storeGetter = store.getters

// request interceptor 请求拦截
instance.interceptors.request.use(
  config => {
    // do something before request is sent
    if (storeGetter.token) {
      config.headers['X-Token'] = storeGetter.token
    }
    config.headers['x-er-tenant-id'] = sessionStorage.getItem('x-er-tenant-id')
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截
instance.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (response.status >= 200 && response.status < 300) {
      if (response.status === LOG_OUT) {
        loginOut()
      }
      return res
    } else {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return null
    }
  },
  error => {
    console.log('err====>' + error) // for debug
    // 身份过期
    if (error.response.status === TOKEN_OVER_CODE) {
      loginOut()
    } else {
      if (error.response.data.code && error.response.data.code !== 'code.undefined') {
        Message({
          message: error.response.data.message || '请求错误，请稍后重试',
          type: 'error',
          duration: 2 * 1000
        })
      } else {
        Message({
          message: '请求错误，请稍后重试',
          type: 'error',
          duration: 2 * 1000
        })
      }
      loginOut()
    }
    return Promise.reject(error)
  }
)

class HTTP_ {
  async GET() {
    return this.handler('get', arguments)
  }
  async POST() {
    return this.handler('post', arguments)
  }
  async DELETE() {
    return this.handler('delete', arguments)
  }
  async PUT() {
    return this.handler('put', arguments)
  }
  async PATCH() {
    return this.handler('patch', arguments)
  }
  async handler(methods, message) {
    try {
      let mes
      message = [...message]
      if (methods === 'get') {
        mes = await instance.get(message[0], {
          params: {
            ...message[1]
          }
        })
      } else if (methods === 'delete') {
        mes = await instance.delete(message[0])
      } else if (methods === 'post') {
        mes = await instance.post(message[0], message[1])
      } else if (methods === 'put') {
        mes = await instance.put(message[0], {
          ...message[1]
        })
      } else if (methods === 'patch') {
        mes = await instance.patch(message[0], {
          ...message[1]
        })
      }
      // 状态码为 200
      return mes

    } catch (error) {
      return null
    }
  }
}

export default new HTTP_()
